const { request, getImageUrl } = require("/utils");
import { TradeStatus, EatingPattern, TradePayResultCode } from '/constants';
import { orderExpiredTime } from '/config'
let timer;
Page({
    data: {
        detail: {},
        orderItems: [],
        statusIcon: '',
        statusDetail: {},
        infoList: [{
                name: '食用方式',
                value: ''
            },
            {
                name: '订单编号',
                value: '',
                copy: true
            },
            {
                name: '支付宝单号',
                value: '',
                copy: true
            },
            {
                name: '下单时间',
                value: ''
            }
        ]
    },
    onLoad({ alipayTradeNo }) {
        this.getOrderDetail(alipayTradeNo);
        my.setCanPullDown({ canPullDown: false });
    },
    async getOrderDetail(alipayTradeNo) {
        const { code, data } = await request.get('/miniapp/order/detail?alipayTradeNo=' + alipayTradeNo);
        if (code !== 200) return;
        const { orderItems, eatingPattern, detail } = data;
        const { status, updatedTime } = data;
        if (status === TradeStatus.Unpaid) {
            const endTime = new Date(updatedTime).getTime() + orderExpiredTime;
            const nowTime = Date.now();
            if (endTime < nowTime) {
                await request.post('/miniapp/order/checkExpired', { alipayTradeNo });
                return my.redirectTo({ url: '/pages/orderDetail/orderDetail?alipayTradeNo=' + alipayTradeNo });
            }
        }
        const statusDetailList = [{
                name: '订单已取消',
                icon: '/assets/imgs/haveCancel.png',
                desKey: '取消时间：',
                desValue: new Date(updatedTime)
                    .toLocaleString()
            },
            { name: '订单待支付', icon: '/assets/imgs/nopayment.png', desKey: '剩余支付时间：', desValue: '00:00:00' },
            {
                name: '订单已支付',
                icon: '/assets/imgs/havePaid.png',
                desKey: '支付时间：',
                desValue: new Date(updatedTime)
                    .toLocaleString()
            }
        ];
        const { infoList } = this.data;
        infoList[0].value = EatingPattern[eatingPattern - 1];
        infoList[1].value = data.orderNumber;
        infoList[2].value = data.alipayTradeNo;
        infoList[3].value = new Date(data.createdTime).toLocaleString();
        this.setData({
            detail: data,
            orderItems: orderItems.map(item => ({
                ...item,
                goods: { ...item.goods, cover: getImageUrl(item.goods.cover) },
                sku: {
                    ...item.sku,
                    images: item.sku.images.map(item =>
                        getImageUrl(item))
                },
            })),
            statusDetail: statusDetailList[status],
            infoList
        });
        if (status === TradeStatus.Unpaid) {
            this.startTimeInterval();
        }
    },
    async startTimeInterval() {
        const { detail, statusDetail } = this.data;
        const { alipayTradeNo } = detail;
        const endTime = new Date(detail.updatedTime).getTime() + orderExpiredTime;
        const padWords = (num) => {
            return num.toString().padStart(2, '0');
        }
        timer = setInterval(async () => {
            const diff = endTime - Date.now();
            const hours = Math.floor(diff / (1000 * 60 * 60));
            const minutes = Math.floor((diff - hours * 1000 * 60 * 60) / (1000 * 60));
            const seconds = Math.floor((diff - hours * 1000 * 60 * 60 - minutes * 1000 * 60) / 1000);
            let value = `${padWords(hours)}:${padWords(minutes)}:${padWords(seconds)}`;
            if (diff <= 0) {
                value = '00:00:00';
                clearInterval(timer);
                await request.post('/miniapp/order/checkExpired', { alipayTradeNo });
                my.redirectTo({ url: '/pages/orderDetail/orderDetail?alipayTradeNo=' + alipayTradeNo });
            }
            this.setData({
                statusDetail: { ...statusDetail, desValue: value }
            });
        }, 1000);
    },
    handleCopy({ target: { dataset: { text } } }) {
        my.setClipboard({
            text,
            success() {
                my.showToast({ content: '已复制' })
            },
            fail(err) {
                my.showToast({ content: '复制失败' });
            }
        });
    },
    async handlePay() {
        my.showLoading({ content: '加载中', mask: true });
        const { alipayTradeNo } = this.data.detail;
        my.tradePay({
            tradeNO: alipayTradeNo,
            success: ({ resultCode }) => {
                try {
                    if (resultCode === TradePayResultCode.Cancel) return my.hideLoading();
                    setTimeout(() => {
                        my.redirectTo({
                            url: '/pages/orderDetail/orderDetail?alipayTradeNo=' +
                                alipayTradeNo
                        });
                    }, 500);
                } catch (e) {
                    my.hideLoading();
                }
            },
            fail: () => {
                my.hideLoading();
            }
        });

    }
});